"""
Kimi API客户端封装
"""
import requests
from django.conf import settings


class KimiClient:
    """Kimi API客户端"""
    
    def __init__(self):
        self.api_key = settings.KIMI_API_KEY
        self.base_url = settings.KIMI_API_BASE_URL
        self.headers = {
            'Authorization': f'Bearer {self.api_key}',
            'Content-Type': 'application/json'
        }
    
    def chat(self, messages, model='moonshot-v1-8k', temperature=0.3):
        """
        调用Kimi聊天API
        
        Args:
            messages: 消息列表 [{'role': 'user', 'content': '...'}, ...]
            model: 模型名称
            temperature: 温度参数
        
        Returns:
            API响应结果
        """
        url = f'{self.base_url}/chat/completions'
        
        payload = {
            'model': model,
            'messages': messages,
            'temperature': temperature
        }
        
        try:
            response = requests.post(url, headers=self.headers, json=payload, timeout=30)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            return {'error': str(e)}
    
    def simple_chat(self, user_message, system_message=None):
        """
        简化的聊天接口
        
        Args:
            user_message: 用户消息
            system_message: 系统提示（可选）
        
        Returns:
            AI回复内容或错误信息
        """
        messages = []
        
        if system_message:
            messages.append({'role': 'system', 'content': system_message})
        
        messages.append({'role': 'user', 'content': user_message})
        
        result = self.chat(messages)
        
        if 'error' in result:
            return None, result['error']
        
        try:
            reply = result['choices'][0]['message']['content']
            return reply, None
        except (KeyError, IndexError):
            return None, 'API响应格式错误'

